import datetime, json
from data.zhihu import ZHIHUHOT
from support.template.page import Template
from support.utils.toolkit import Log
from http.server import HTTPServer,BaseHTTPRequestHandler

class TaskHttpServer(HTTPServer):
    def setScheduler(self, scheduler):
        self.scheduler = scheduler
    def getScheduler(self):
        return self.scheduler
    
    def run(port, scheduler):
        try:
            server = TaskHttpServer(('0.0.0.0', port), TaskResquest)
            server.setScheduler(scheduler)
            Log.i("Task Server is running on [{}]".format(port))
            server.serve_forever()
        except Exception:
            server.socket.close
            server.server_close    

class TaskResquest(BaseHTTPRequestHandler):    
    def log_message(self, format: str, *args):
        return   
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()
        today = datetime.date.today()
        if(self.path == "/favicon.ico"):
            pass
        elif(self.path.startswith("/top")):
            #self.wfile.write(Template.createTemplate(ZHIHUHOT.TAG, self.server.getScheduler().getData(ZHIHUHOT.TAG, 10, year=today.year, month=today.month, day=today.day)))
            self.wfile.write(json.dumps(self.server.getScheduler().getData(ZHIHUHOT.TAG, 10, year=today.year, month=today.month, day=today.day)).encode())
        self.wfile.flush()
        # self.wfile.close()
        return
